// ^2_3^(220102) user-用户
import storage from 'store'
import { login, getInfo, logout } from '@/api/login'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { welcome } from '@/utils/util'
import { basicSetting, changePass } from '@/api/admin'

// user(用户)状态
const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_BASIC: (state, { nickname, profile, email, avatar }) => {
      state.info.nickname = nickname
      state.info.profile = profile
      state.info.email = email
      state.info.avatar = avatar
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_STRENGTH: (state, strength) => {
      state.info.strength = strength
    }
  },

  actions: {
    // ^2_3^登录
    Login ({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          console.log('>response', response)

          if (response.code === 0) {
            const result = response.data
            storage.set(ACCESS_TOKEN, result.token, 2 * 60 * 60 * 1000)
            commit('SET_TOKEN', result.token)
            resolve()
          } else {
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    // ^2_3^获取用户信息(TODO)
    GetInfo ({ commit }) {
      // Promise
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const result = response.result || response.data
          // console.log('>GetInfo', result)

          if (result.role && result.role.permissions.length > 0) {
            const role = result.role
            role.permissions = result.role.permissions
            const actions = []
            role.permissions.map(per => {
              // ~~~
              // 模拟数据处理
              // if (per.actionEntitySet != null && per.actionEntitySet.length > 0) {
              //   const action = per.actionEntitySet.map(action => { return action.action })
              //   per.actionList = action
              // }
              // ~~~
              // ^2_3^自定义数据处理
              if (per.is_menu === 0) {
                  actions.push(per.app + '/' + per.controller + '/' + per.action)
              }
            })
            role.actions = actions
            // ~~~
            // 模拟数据处理
            // role.permissionList = role.permissions.map(permission => { return permission.permissionId })
            // ~~~
            commit('SET_ROLES', result.role)
            commit('SET_INFO', result)
          } else {
            reject(new Error('getInfo: roles must be a non-null array !'))
          }

          commit('SET_NAME', { name: result.name, welcome: welcome() })
          commit('SET_AVATAR', result.avatar)

          console.log('>GetInfo 进入', result)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // ^2_3^登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          storage.remove(ACCESS_TOKEN)
          resolve()
        }).catch(() => {
          resolve()
        }).finally(() => {
        })
      })
    },

    // 个人设置
    BasicSetting ({ commit, state }, basicInfo) {
      return new Promise((resolve, reject) => {
        basicSetting(basicInfo).then(response => {
          console.log('basic response', response)
          if (response.code === 0) {
            const data = response.data

            const basic = {
              avatar: data['avatar'],
              nickname: data['nickname'],
              email: data['email'],
              profile: data['profile']
            }
            commit('SET_BASIC', basic)

            resolve(response)
          } else {
            reject(response)
            // reject(new Error('basicSetting: ' + response.msg))
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

    SetAvatar ({ commit, state }, avatarUrl) {
      commit('SET_AVATAR', avatarUrl)
    },

    ChangePass ({ commit, state }, params) {
      return new Promise((resolve, reject) => {
        changePass(params).then(res => {
          console.log('ChangePass', res)
          if (res.code === 0) {
            commit('SET_STRENGTH', res.data.strength)
            resolve(res)
          } else {
            reject(res)
          }
        })
      })
    }
  }
}

export default user
